package com.comtrade.activities;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.comtrade.ilserver.tasks.BeaconServer;
import com.comtrade.ilserver.tasks.GetBeaconTask;
import com.comtrade.ilserver.tasks.GetSpaceTask;
import com.comtrade.ilserver.tasks.Space;
import com.comtrade.ilserver.tasks.User;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.example.beaconapk.R;


public class GuideActivity extends Activity {
	private static final String TAG = GuideActivity.class.getSimpleName();
	
	private static final int REQUEST_ENABLE_BT = 1234;
	private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid",
			null, null, null);

	private BeaconManager beaconManager;
	
	public static final String MyPREFERENCES = "MyPrefs" ;
	public static final String URL = "URL";
	public static final String Name = "Username";
	public static final String Password = "Passwd";
	private  String url="";
	private String name="";
	private String passwd="";
	SharedPreferences sharedpreferences;
	
	Bitmap bitmap;
	Space sp;
	private boolean indicator=false;

	private ProgressBar mProgress;

	Intent i;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		i = new Intent(GuideActivity.this,DeviceActivity.class);
		Intent lastIntent = getIntent();
		
		User user = (User) lastIntent.getParcelableExtra(User.EXTRA);
		i.putExtra(User.EXTRA, user);
		Log.d("userGuide", "" + user.toString());
		//i.putExtra(User.EXTRA, lastIntent.getParcelableExtra(User.EXTRA));
		//Log.d("userGuide",""+lastIntent.getParcelableExtra(User.EXTRA));
		setContentView(R.layout.activity_guide);
		sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
		if (sharedpreferences.contains(URL))
		{
			url="http://"+sharedpreferences.getString(URL, "");
		}
		if (sharedpreferences.contains(Name))
		{
			name=sharedpreferences.getString(Name, "");

		}
		if (sharedpreferences.contains(Password))
		{
			passwd=sharedpreferences.getString(Password, "");

		}
		
		ProgressBar mProgress = (ProgressBar) findViewById(R.id.progressBar1);
		mProgress.incrementProgressBy(10);

		
		


		//String text = i.getExtras().getString();
		String text = "Place your device near iBeacon";
		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setText(text);
		
		
		
		beaconManager = new BeaconManager(this);
		beaconManager.setRangingListener(new BeaconManager.RangingListener() {
			@Override
			public void onBeaconsDiscovered(Region region, final List<Beacon> rangedBeacons) {
				// Note that results are not delivered on UI thread.
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// Just in case if there are multiple beacons with the same uuid, major, minor.
						
						// moze da zasere sve !!!!!!
						/*
						try {
							beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
						} catch (RemoteException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						*/
						if(indicator == false){
						Beacon foundBeacon = null;
						
						for (Beacon rangedBeacon : rangedBeacons) {
							if (rangedBeacon.getMacAddress() != null) {
								foundBeacon = rangedBeacon;
							}
						}
						if (foundBeacon != null) {
							 indicator=true;
							foundBeacon= rangedBeacons.get(0);
							
							//Toast.makeText(GuideActivity.this, foundBeacon.getMacAddress(),
									//Toast.LENGTH_SHORT).show();
							
							
							
							Toast.makeText(GuideActivity.this, "iBeacon found !",
							Toast.LENGTH_SHORT).show();
							//i.putExtra("Ime",et.getText().toString());
							//startActivity(i);
							
							GetBeaconTask task1 = new GetBeaconTask();
							// TODO shared prefs
							task1.setUsername(name);
							task1.setPassword(passwd);
							task1.setMacAddress(foundBeacon.getMacAddress());
							task1.execute(url+":8080/ils/rest/getBeacon");
							long spaceid=-99;
							try {
								BeaconServer beacons = BeaconServer.fromJSON(task1.get());
								spaceid = beacons.getSid();
							} catch (InterruptedException e) {
								// 
								e.printStackTrace();
							} catch (ExecutionException e) {
								// 
								e.printStackTrace();
							}
							
							GetSpaceTask task2 = new GetSpaceTask();
							
							// TODO adsa
							task2.setUsername(name);
							task2.setPassword(passwd);
							if(spaceid != -99) task2.setSpaceId(spaceid);
							task2.execute(url+":8080/ils/rest/getSpace");
							
							try{
								final Space sp = Space.fromJSON(task2.get());
								
                            					    
							
							Log.d("SPEJS", sp.getTitle());
							//Toast.makeText(GuideActivity.this, sp.getTitle(),
							//Toast.LENGTH_SHORT).show();
							i.putExtra("SPACE",sp);
							
							new Thread(new Runnable() {
								 
								@Override
								public void run() {
									//Intent i = new Intent(GuideActivity.this,DeviceActivity.class);
									
									Log.d("AAAA", "1");
									// TODO adsa
									URL url_value;
									ByteArrayOutputStream stream = new ByteArrayOutputStream();
											
											try {
												url_value=new URL(url+":8080/ils/"+sp.getMapurl());
												Log.d("LINK", url_value.toString());
												 bitmap = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
												 Log.d("AAAA", "2");
												
											} catch (MalformedURLException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										
									
										
										Log.d("Ime", i.toString());
									    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
									    byte[] byteArray=stream.toByteArray();
					                   i.putExtra("image",byteArray);
					                  
					                   startActivity(i);
								}
							}).start();
							//startActivity(i);
							} catch (InterruptedException e) {
								// 
								e.printStackTrace();
							} catch (ExecutionException e) {
								// 
								e.printStackTrace();
							}
							
						}
						else {
							//Toast.makeText(GuideActivity.this, "iBeacons not found !",
									//Toast.LENGTH_SHORT).show();

						}
					}
					}

					

							
					
				});
				
				
				
			}
			
		});
		
		
		
		
		
	}

	@Override
	protected void onStart() {
		super.onStart();

		// iBeacons
		// Check if device supports Bluetooth Low Energy.
		if (!beaconManager.hasBluetooth()) {
			Toast.makeText(this, "Device does not have Bluetooth Low Energy",
					Toast.LENGTH_LONG).show();
			return;
		}

		// If Bluetooth is not enabled, let user enable it.
		if (!beaconManager.isBluetoothEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			connectToService();
		}

	}

	private void connectToService() {
		beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
			@Override
			public void onServiceReady() {
				try {
					beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
				} catch (RemoteException e) {
					Toast.makeText(
							GuideActivity.this,
							"Cannot start ranging, something terrible happened",
							Toast.LENGTH_LONG).show();
					Log.e(TAG, "Cannot start ranging", e);
				}
			}
		});
	}
	@Override
	protected void onStop() {
		//Ovo mozda treba u onDestroy() :D
		try {

			beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
		} catch (RemoteException e) {
			//e.printStackTrace();
		}
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		beaconManager.disconnect();
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT) {
			if (resultCode == Activity.RESULT_OK) {
				connectToService();
			} else {
				Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
				.show();
				getActionBar().setSubtitle("Bluetooth not enabled");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
